import {CATEGORIES_STORAGE_KEY, STORAGE_KEY, TAGS_STORAGE_KEY, useMapStore} from "./index";

// 从focusany.dbStorage加载数据
export const loadFromStorage = () => {
    const store = useMapStore();

    try {
        console.log("开始加载数据...");

        // 加载地址数据
        const storedData = focusany.dbStorage.getItem(STORAGE_KEY);
        if (storedData && Array.isArray(storedData)) {
            store.addressList = storedData.map((item: any) => ({
                ...item,
                point: new window.BMapGL.Point(item.point.lng, item.point.lat),
                status: item.status || "unchecked",
                categoryId: item.categoryId || "default",
            }));
            console.log("加载地址数据:", store.addressList.length, "条");

            // 如果有地址数据，默认显示地址列表tab
            if (store.addressList.length > 0) {
                store.setActiveTab("list");
            }
        }

        // 加载标签数据
        const storedTags = focusany.dbStorage.getItem(TAGS_STORAGE_KEY);
        if (storedTags && Array.isArray(storedTags)) {
            store.addressTags = storedTags;
            console.log("加载标签数据:", store.addressTags.length, "个");
        }

        // 加载分类数据
        const storedCategories = focusany.dbStorage.getItem(CATEGORIES_STORAGE_KEY);
        if (storedCategories && Array.isArray(storedCategories)) {
            store.addressCategories = storedCategories;
            console.log("加载分类数据:", store.addressCategories.length, "个");
        }

        // 加载UI状态
        store.loadUIState();
        console.log("加载UI状态完成，左侧面板折叠状态:", store.isLeftPanelCollapsed);
    } catch (error) {
        console.error("数据加载失败:", error);
        // 清除损坏的数据
        focusany.dbStorage.removeItem(STORAGE_KEY);
        focusany.dbStorage.removeItem(TAGS_STORAGE_KEY);
        focusany.dbStorage.removeItem(CATEGORIES_STORAGE_KEY);
    }
};

// 保存地址数据
export const saveToStorage = () => {
    const store = useMapStore();

    try {
        const data = store.addressList.map(item => ({
            ...item,
            point: {lng: item.point.lng, lat: item.point.lat},
        }));
        focusany.dbStorage.setItem(STORAGE_KEY, data);
        console.log("保存地址数据:", data.length, "条");
    } catch (error) {
        console.error("保存地址数据失败:", error);
    }
};

// 保存标签数据
export const saveTagsToStorage = () => {
    const store = useMapStore();

    try {
        focusany.dbStorage.setItem(TAGS_STORAGE_KEY, store.addressTags);
        console.log("保存标签数据:", store.addressTags.length, "个");
    } catch (error) {
        console.error("保存标签数据失败:", error);
    }
};

// 保存分类数据
export const saveCategoriesToStorage = () => {
    const store = useMapStore();

    try {
        focusany.dbStorage.setItem(CATEGORIES_STORAGE_KEY, store.addressCategories);
        console.log("保存分类数据:", store.addressCategories.length, "个");
    } catch (error) {
        console.error("保存分类数据失败:", error);
    }
};
